﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace NanoMvvm.Collections
{
    public class WeakCollection<T> : ICollection<T> where T : class
    {
        private const int CleanupMark = 15;

        private readonly List<WeakReference<T>> items;

        private volatile int accessCounter;

        public WeakCollection()
        {
            items = new List<WeakReference<T>>();
        }

        public int Count
        {
            get
            {
                ProcessAccess();
                return items.Count;
            }
        }

        public bool IsReadOnly
        {
            get
            {
                return false;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void CleanupReferences()
        {
            for (int i = items.Count - 1; i >= 0; i--)
            {
                if (!items[i].IsTargetAlive)
                {
                    items.RemoveAt(i);
                }
            }
        }

        public IEnumerator<T> GetEnumerator()
        {
            ProcessAccess();

            return items.Where(reference => reference.IsTargetAlive).Select(reference => reference.Target).GetEnumerator();
        }

        public void Add(T item)
        {
            ProcessAccess();
            items.Add(new WeakReference<T>(item));
        }

        public void Clear()
        {
            items.Clear();
        }

        public bool Contains(T item)
        {
            ProcessAccess();

            return items.Any(reference => reference.IsTargetAlive && Equals(reference.Target, item));
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            ProcessAccess();
            items.Where(wr => wr.IsTargetAlive).ToArray().CopyTo(array, arrayIndex);
        }

        public bool Remove(T item)
        {
            ProcessAccess();

            for (int i = 0; i < items.Count; i++)
            {
                if (!items[i].IsTargetAlive || !Equals(items[i].Target, item))
                {
                    continue;
                }

                items.RemoveAt(i);
                return true;
            }

            return false;
        }

        private void ProcessAccess()
        {
            accessCounter++;
            if (accessCounter >= CleanupMark)
            {
                CleanupReferences();
            }
        }
    }
}